import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useTabStore = defineStore('tab', () => {
  const home = {
    path:'/home',
    name:'home',
    meta:{title:'首页',icon:'house',type:'primary'}
  }
  const menus = ref([home])
  const currentMenu=ref(home)

  // 选择菜单
  const selectMenu=(val)=>{
    console.log('选择菜单',val)
    currentMenu.value=val
    // 思路：点击菜单后记录下当前点击的菜单把他添加到 menus数组中，要去重
    const isExists = menus.value.some(i=>i.path ===val.path)
    !isExists&&menus.value.push(val)
  }

  // 关闭tag
  const closeTag = (tag)=>{
    const index = menus.value.indexOf(tag)
    const menu =  menus.value[index]
    if(menu===currentMenu.value)
      currentMenu.value = menus.value[index-1]??home
    menus.value.splice(index,1)
  }
  // 关闭全部或关闭其他
  const handleTags = (command) => {
    console.log(menus.value)
    if (command === "other") {
      menus.value = menus.value.filter(
        (i) => i.path == currentMenu.value.path || i.path === "/home"
      );
    } else {
      clearTabs()
    }
  }

  // 退出清空tab
  const clearTabs = ()=>{
    menus.value = menus.value.filter((i) => i.path === "/home");
      currentMenu.value = menus.value[0];
  }
  return { menus, currentMenu, selectMenu,closeTag,handleTags,clearTabs }
},{
  persist:true
})
